<?php
/**
 * 项目行为扩展：根据IP设置语言及货币
 * @category   App
 * @package  App
 * @subpackage  Behavior
 * @author   cjli
 */
class CheckIpBehavior extends Behavior
{
	// 行为参数定义（默认值） 可在项目配置中覆盖
    protected $options   =  array(
        'CHECK_IP_CHANGE_LANGUAGE_ON' => false,   // 是否开启IP检测
    	'CHECK_IP_LANG_AUTO_DETECT'   => true,   // 自动侦测语言 开启IP检测功能后有效
        'VAR_LANGUAGE'          => 'l',		// 默认语言切换变量
        );

    // 行为扩展的执行入口必须是run
    public function run(&$params)
    {
    	if (!C('CHECK_IP_CHANGE_LANGUAGE_ON')){
      	return;
      }

      //$this->checkIp_toUrl();
     	//$this->checkIp();
     	$this->checkLanguage();
    }

    /**
     * 第一次进入 进行IP检测 跳到相应二级域名
	 */
    private function checkIp_toUrl()
    {
        $domain_prefix = "www";

        //2014-12-16 取消小语种
       	if( $_SERVER['HTTP_HOST'] != '58.215.187.187:83' && $_SERVER['HTTP_HOST'] != 'www.'.APP_DOMAIN ){
       		//法语跳到www.ownonly.fr
            if($_SERVER['HTTP_HOST'] == 'fr.'.APP_DOMAIN){
				send_http_status(301);
				Header("Location: http://www.ownonly.fr");
				return;
            }
			$url = preg_replace('/\?l=\w+&?/','',$_SERVER['REQUEST_URI']);
			send_http_status(301);
			Header("Location: http://".$domain_prefix.".".APP_DOMAIN.$url);
    	}
        return;
        //2014-12-16 取消小语种

    	if( ($_SERVER['HTTP_HOST'] == 'www.'.APP_DOMAIN && !cookie('self_language_set') && $_SERVER['HTTP_HOST'] != '58.215.187.187')
    	    || $_SERVER['HTTP_HOST'] == APP_DOMAIN ){
	   		//$ip = "98.126.140.226";//US
	   		//$ip = '62.75.163.74';//DE
	   	    //$ip = '78.192.70.254';//FR
	        $ip = get_client_ip();
	        //加载IP库
	        include(VENDOR_PATH."GeoIp/geoip.inc");
	        $gi = geoip_open(VENDOR_PATH."GeoIp/GeoIP.dat",GEOIP_STANDARD);
	        $geo_code = geoip_country_code_by_addr($gi, $ip);

            //dump($geo_code);exit;
	        //获取系统语言列表
		   	$language_id = C('language_id');
			if(S('language_list')){
				$languageList = S('language_list');
			}else{
				$lang_db = D('language');
				$languageList = $lang_db->field('id,name,code,directory,locale')->where('status=1')->order('listorder DESC')->select();
				S('language_list', $languageList);
			}

			//检查域名前缀是否真实有效
			if($languageList){
				foreach ($languageList as $lan){
					if(in_array($geo_code, explode(',', strtoupper($lan['locale'])))){
                        if($lan['directory'] != "en-us") $domain_prefix = $lan['directory'];
						break;
					}
				}
			}

    	}

        //提到外面是解决第一次进二级域名，切换到www时开始跳转到ip所在区域的问题
    	//30天内只自动跳转一次
        cookie('self_language_set', 1,'expire=2592000&path=/&domain='.APP_DOMAIN);

        if( $domain_prefix != "www" || $_SERVER['HTTP_HOST'] == APP_DOMAIN ){
			$url = preg_replace('/\?l=\w+&?/','',$_SERVER['REQUEST_URI']);
			//send_http_status(301);
			Header("Location: http://".$domain_prefix.".".APP_DOMAIN.$url);
		}

    }
    /**
     * IP检测
     */
    private function checkIp()
    {

    	if(! cookie('think_language_id')){

//    		$ip = "98.126.140.226";//US
//    		$ip = '62.75.163.74';//DE
//    		$ip = '78.192.70.254';//FR
	      $ip = get_client_ip();
	     //加载IP库
	      include(VENDOR_PATH."GeoIp/geoip.inc");
	      $gi = geoip_open(VENDOR_PATH."GeoIp/GeoIP.dat",GEOIP_STANDARD);
	      $geo_code = geoip_country_code_by_addr($gi, $ip);
//dump($geo_code);exit;
	      //获取系统语言列表
		   	$language_id = C('language_id');
				if(S('language_list')){
					$languageList = S('language_list');
				}else{
					$lang_db = D('language');
					$languageList = $lang_db->field('id,name,code,directory,locale')->where('status=1')->order('listorder DESC')->select();
					S('language_list', $languageList);
				}

				if($languageList){
					foreach ($languageList as $lan){
						if(in_array($geo_code, explode(',', strtoupper($lan['locale'])))){
							$language_id = $lan['id'];
							 cookie('think_language',$lan['directory'],3600);
							 cookie('think_language_id',$language_id,3600);
							break;
						}
					}
				}
				if(! cookie('think_language_id')){
					cookie('think_language_id',$language_id,3600);
					cookie('think_language',C('DEFAULT_LANG'),3600);
				}
    	}
    }

		/**
     * 语言检查
     * 检查浏览器支持语言，并自动加载语言包
     * @access private
     * @return void
     */
    private function checkLanguage() {
        // 不开启语言包功能，仅仅加载框架语言文件直接返回
    	if (!C('CHECK_IP_CHANGE_LANGUAGE_ON')){
      	return;
      }
        $langSet = C('DEFAULT_LANG');
        // 启用了语言包功能
        // 根据是否启用自动侦测设置获取语言选择
		//url后面的参数替换为空的字符串
		$url = preg_replace('/\?l=\w+&?/','',$_SERVER['REQUEST_URI']);
        if (C('CHECK_IP_LANG_AUTO_DETECT')){
        if(isset($_GET[C('VAR_LANGUAGE')])){
			//$langSet = $_GET[C('VAR_LANGUAGE')];
			if($_GET[C('VAR_LANGUAGE')]=='es'){
				send_http_status(301);
				Header("Location: http://es.".APP_DOMAIN.$url);
			}elseif($_GET[C('VAR_LANGUAGE')]=='fr'){
				send_http_status(301);
				Header("Location: http://fr.".APP_DOMAIN.$url);
			}elseif($_GET[C('VAR_LANGUAGE')]=='jp'){
				send_http_status(301);
				Header("Location: http://jp.".APP_DOMAIN.$url);
			}elseif($_GET[C('VAR_LANGUAGE')]=='pt'){
				send_http_status(301);
				Header("Location: http://pt.".APP_DOMAIN.$url);
			}elseif($_GET[C('VAR_LANGUAGE')]=='de'){
				send_http_status(301);
				Header("Location: http://de.".APP_DOMAIN.$url);
			}elseif($_GET[C('VAR_LANGUAGE')]=='ru'){
				send_http_status(301);
				Header("Location: http://ru.".APP_DOMAIN.$url);
			}elseif($_GET[C('VAR_LANGUAGE')]=='it'){
				send_http_status(301);
				Header("Location: http://it.".APP_DOMAIN.$url);
			}
		}
	}
        if (C('CHECK_IP_LANG_AUTO_DETECT')){
			//dump(C('CHECK_IP_LANG_AUTO_DETECT'));exit;


            if($_SERVER['HTTP_HOST'] == 'es.'.APP_DOMAIN){
				cookie('think_language','es');
				$langSet = 'es';
				$this->get_language_id('es');
			}elseif($_SERVER['HTTP_HOST'] == 'fr.'.APP_DOMAIN){
				cookie('think_language','fr');
				$langSet = 'fr';
				$this->get_language_id('fr');
			}elseif($_SERVER['HTTP_HOST'] == 'www.'.APP_DOMAIN){
				cookie('think_language','zh-cn');
				$langSet = 'zh-cn';
				$this->get_language_id('zh-cn');
			}elseif($_SERVER['HTTP_HOST'] == 'jp.'.APP_DOMAIN){
				cookie('think_language','jp');
				$langSet = 'jp';
				$this->get_language_id('jp');
			}elseif($_SERVER['HTTP_HOST'] == 'de.'.APP_DOMAIN){
				cookie('think_language','de');
				$langSet = 'de';
				$this->get_language_id('de');
			}elseif($_SERVER['HTTP_HOST'] == 'pt.'.APP_DOMAIN){
				cookie('think_language','pt');
				$langSet = 'pt';
				$this->get_language_id('pt');
			}elseif($_SERVER['HTTP_HOST'] == 'it.'.APP_DOMAIN){
				cookie('think_language','it');
				$langSet = 'it';
				$this->get_language_id('it');
			}elseif($_SERVER['HTTP_HOST'] == 'ru.'.APP_DOMAIN){
				cookie('think_language','ru');
				$langSet = 'ru';
				$this->get_language_id('ru');
			}elseif(cookie('think_language')){// 获取上次用户的选择
                $langSet = cookie('think_language');
				$this->get_language_id($langSet);
            }elseif(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){// 自动侦测浏览器语言
/*                preg_match('/^([a-z\d\-]+)/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $matches);
                $langSet = $matches[1];
                cookie('think_language',$langSet,3600);
                 $this->get_language_id($langSet);*/
				cookie('think_language','zh-cn');
				$langSet = 'zh-cn';
				$this->get_language_id('zh-cn');
            }
            //获取语言列表
            $languageList = S('language_list');
		        if($languageList){
		        	$lang_list = null;
							foreach ($languageList as $lan){
								 $lang_list .= $lan['directory'].',';
							}
						}
            if(false === stripos($lang_list, $langSet)) { // 非法语言参数
                $langSet = C('DEFAULT_LANG');
                cookie('think_language_id',C('language_id'),3600);
            }
        }
        // 定义当前语言
        define('LANG_SET', strtolower($langSet));
        // 读取项目公共语言包
        if (is_file(LANG_PATH.LANG_SET.'/common.php'))
            L(include LANG_PATH.LANG_SET.'/common.php');
        $group = '';
        $lang_path    =   C('APP_GROUP_MODE')==1 ? BASE_LIB_PATH.'Lang/'.LANG_SET.'/' : LANG_PATH.LANG_SET.'/';
        // 读取当前分组公共语言包
        if (defined('GROUP_NAME')){
            if (is_file($lang_path.GROUP_NAME.'.php'))
                L(include $lang_path.GROUP_NAME.'.php');
            $group = GROUP_NAME.C('TMPL_FILE_DEPR');
        }
        // 读取当前模块语言包
        if (is_file($lang_path.$group.strtolower(MODULE_NAME).'.php'))
            L(include $lang_path.$group.strtolower(MODULE_NAME).'.php');
    }

    /**
     * 根据语言包选择语言ID
     * @param string $langset 语言包名称
     */
    private function get_language_id($langset)
    {
		if(S('language_list')){
			$languageList = S('language_list');
		}else{
			$lang_db = D('language');
			$languageList = $lang_db->field('id,name,code,directory,locale')->where('status=1')->order('listorder DESC')->select();
			S('language_list', $languageList);
		}
    	foreach ($languageList as $lang){
    		if($langset == $lang['directory']){
    			cookie('think_language_id',$lang['id'],3600);
				cookie('think_language_name',$lang['name'],3600);
    			break;
    		}
    	}
    }
}